<template>
  <div class="community-page">
    <van-nav-bar right-text="发表" @click-right="showPublish" />
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div class="feed-list">
        <div v-for="(item, index) in list" :key="index" class="feed-item">
          <div class="feed-header">
            <img :src="item.avatar" alt="头像" class="avatar" />
            <div class="nickname">{{ item.nickname }}</div>
          </div>
          <div class="feed-content">
            <p>{{ item.text }}</p>
            <div class="images" v-if="item.images && item.images.length">
              <img
                v-for="(img, idx) in item.images"
                :key="idx"
                :src="img"
                alt="图片"
                class="feed-image"
              />
            </div>
          </div>
          <div class="feed-footer">
            <van-button
              type="primary"
              plain
              hairline
              size="small"
              :icon="item.liked ? 'like' : 'like-o'"
              @click="toggleLike(item)"
            >
              {{ item.likes }}
            </van-button>
            <van-button
              type="info"
              plain
              hairline
              size="small"
              icon="comment-o"
              @click="showComment(item)"
            >
              {{ item.comments }}
            </van-button>
          </div>
          <div class="comments-section" v-show="item.showComments">
            <van-field
              v-model="item.newComment"
              rows="1"
              autosize
              type="textarea"
              placeholder="留下你的评论..."
              @keyup.enter="addComment(item)"
            />
            <div class="comments-list">
              <div
                v-for="(comment, cidx) in item.commentsList"
                :key="cidx"
                class="comment-item"
              >
                <span class="commentator">{{ comment.user }}:</span>
                <span class="comment-content">{{ comment.text }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-pull-refresh>
    <van-popup
      v-model:show="publishing"
      position="bottom"
      :style="{ height: '50%' }"
    >
      <van-field
        v-model="newPost.text"
        rows="5"
        autosize
        type="textarea"
        placeholder="这一刻的想法..."
      />
      <van-uploader v-model="newPost.images" multiple :max-count="9" />
      <van-button type="primary" block @click="publishPost">发布</van-button>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Toast, Popup, Field, Uploader, Button } from "vant";
import { getDynamicList, addDynamic, addComment as addCommentApi, getCommentList } from '../services/community';
import { getCurrentUser } from '../services/user';

const list = ref([]);
const currentUser = ref(null);

onMounted(async () => {
  try {
    const userInfo = await getCurrentUser();
    currentUser.value = userInfo;
    await loadDynamics();
  } catch (error) {
    Toast.fail('获取数据失败');
  }
});

const loadDynamics = async () => {
  try {
    const res = await getDynamicList({});
    if (res?.code === 0) {
      list.value = res.data.map(item => ({
        id: item.id,
        avatar: item.user.avatarUrl,
        nickname: item.user.username,
        text: item.content,
        images: item.images || [],
        liked: false,
        likes: item.likes || 0,
        comments: item.comments || 0,
        showComments: false,
        commentsList: [],
        newComment: "",
      }));
    }
  } catch (error) {
    Toast.fail('获取动态列表失败');
  }
};

    nickname: "Kiki",
    text: "今天天气不错，出去散步了。",
    images: ["https://picsum.photos/100/100?random=3"],
    liked: false,
    likes: 12,
    comments: 3,
    showComments: false,
    commentsList: [
      { user: "李四", text: "确实不错，羡慕你的好天气！" },
      { user: "王五", text: "我也想出去散步。" },
    ],
    newComment: "",
  },
  {
    avatar: "https://randomuser.me/api/portraits/men/6.jpg",
    nickname: "felisha",
    text: "今天天气不错，出去散步了。",
    images: ["https://picsum.photos/100/100?random=1"],
    liked: false,
    likes: 12,
    comments: 3,
    showComments: false,
    commentsList: [
      { user: "李四", text: "确实不错，羡慕你的好天气！" },
      { user: "王五", text: "我也想出去散步。" },
    ],
    newComment: "",
  },
  {
    avatar: "https://randomuser.me/api/portraits/men/1.jpg",
    nickname: "charlie",
    text: "今天天气不错，出去散步了。",
    images: ["https://picsum.photos/100/100?random=2"],
    liked: false,
    likes: 12,
    comments: 3,
    showComments: false,
    commentsList: [
      { user: "李四", text: "确实不错，羡慕你的好天气！" },
      { user: "王五", text: "我也想出去散步。" },
    ],
    newComment: "",
  },
]);

const refreshing = ref(false);
const publishing = ref(false);
const newPost = ref({
  text: "",
  images: [],
});

const onRefresh = async () => {
  try {
    await loadDynamics();
    refreshing.value = false;
    Toast.success("刷新成功");
  } catch (error) {
    refreshing.value = false;
    Toast.fail("刷新失败");
  }
};

const toggleLike = (item) => {
  item.liked = !item.liked;
  item.likes += item.liked ? 1 : -1;
};

const showComment = async (item) => {
  item.showComments = !item.showComments;
  if (item.showComments && item.commentsList.length === 0) {
    try {
      const res = await getCommentList(item.id);
      if (res?.code === 0) {
        item.commentsList = res.data.map(comment => ({
          user: comment.user.username,
          text: comment.content
        }));
      }
    } catch (error) {
      Toast.fail('获取评论失败');
    }
  }
};

const addComment = async (item) => {
  if (item.newComment.trim()) {
    try {
      const res = await addCommentApi({
        dynamicId: item.id,
        content: item.newComment
      });
      if (res?.code === 0) {
        item.commentsList.push({
          user: currentUser.value.username,
          text: item.newComment
        });
        item.comments += 1;
        item.newComment = "";
        Toast.success('评论成功');
      }
    } catch (error) {
      Toast.fail('评论失败');
    }
  }
};

const showPublish = () => {
  publishing.value = true;
};

const publishPost = async () => {
  if (newPost.value.text.trim() || newPost.value.images.length) {
    try {
      const imageUrls = await Promise.all(
        newPost.value.images.map(async (file) => {
          const formData = new FormData();
          formData.append('file', file.file);
          const res = await imageUpload(formData);
          return res.data.url;
        })
      );

      const res = await addDynamic({
        content: newPost.value.text,
        images: imageUrls
      });

      if (res?.code === 0) {
        await loadDynamics();
        newPost.value.text = "";
        newPost.value.images = [];
        publishing.value = false;
        Toast.success("发布成功");
      }
    } catch (error) {
      Toast.fail('发布失败');
    }
  } else {
    Toast.fail("内容不能为空");
  }
};
</script>

<style scoped>
.community-page {
  background-color: #f8f9fa;
  padding: 16px;
}

.feed-item {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
  overflow: hidden;
  padding: 16px;
}

.feed-header {
  display: flex;
  align-items: center;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 12px;
}

.nickname {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.feed-content {
  margin-top: 12px;
}

.feed-content p {
  font-size: 14px;
  line-height: 1.5;
  color: #666;
}

.images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 12px;
}

.feed-image {
  width: 80%;
  border-radius: 8px;
}

.feed-footer {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 16px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #eaeaea;
}

.feed-footer .van-button {
  font-size: 14px;
}
</style>
